﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace WcfLogger
{
	public class WcfLogger
	{
		private StreamWriter sw;
		private static WcfLogger m_instance;
		private static object syncRoot = new object();

		private WcfLogger()
		{

		}

		public static WcfLogger Instance
		{
			get
			{
				lock (syncRoot)
				{
					if (m_instance == null)
						m_instance = new WcfLogger();
				}
				return m_instance;
			}
		}

		public void WriteToLog(string[] data)
		{
			lock (syncRoot)
			{
				BackupLog(@"C:\WCFlog.txt", @"C:\WcfLog.Backup.zip");

				using (sw = new StreamWriter(@"C:\WCFlog.txt", true, Encoding.UTF8))
				{
					StringBuilder sb = new StringBuilder();

					sb.Append(string.Format("[{0}] ", DateTime.Now.ToString("dd.MM.yy hh:mm")));
					foreach (string s in data)
					{
						sb.AppendFormat("{0} \t", s);
					}
					sb.Append(Environment.NewLine);
					sw.WriteLine(sb.ToString());
					sw.Flush();
				}
			}
		}

		public void BackupLog(string sourceFile, string destFile)
		{
			using (FileStream fsIn = new FileStream(sourceFile, FileMode.Open))
			{
				long fileLenMb = (fsIn.Length / 1024 / 1024);
				if (fileLenMb < 2)
				{
					return;
				}

				using (FileStream fsOut = new FileStream(destFile, FileMode.Create))
				{
					using (GZipStream zipStream = new GZipStream(fsOut, CompressionMode.Compress))
					{
						byte[] buffer = new byte[1024];
						while (true)
						{
							int bytesRead = fsIn.Read(buffer, 0, buffer.Length);
							zipStream.Write(buffer, 0, bytesRead);

							if (bytesRead != buffer.Length)
								break;
						}
						zipStream.Flush();
						fsOut.Flush();
					}
				}
			}
		}
	}
}
